package cn.cj.erp.common.security.security.service;

import cn.cj.erp.bo.system.SysRoleBo;
import cn.cj.erp.bo.system.SysUserBo;
import cn.cj.erp.common.utils.UserUtils;
import cn.cj.erp.service.system.SysRoleService;
import cn.cj.erp.service.system.SysUserService;
import cn.hutool.core.collection.CollectionUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 用户权限处理
 */
@Service
public class PermissionService {
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysUserService sysUserService;

    /**
     * 获取角色数据权限
     *
     * @param user 用户信息
     * @return 角色权限信息
     */
    public Set<String> getRolePermission(SysUserBo user) {
        Set<String> roles = new HashSet<>();
        // 管理员拥有所有权限
        if (UserUtils.isAdmin(user.getUserId())) {
            roles.add("admin");
        } else {
            Set<String> perms = sysUserService.listRolePermById(user.getUserId());
            roles.addAll(perms);
        }
        return roles;
    }

    /**
     * 获取菜单数据权限
     *
     * @param user 用户信息
     * @return 菜单权限信息
     */
    public Set<String> getMenuPermission(SysUserBo user) {
        Set<String> perms = new HashSet<>();
        // 管理员拥有所有权限
        if (UserUtils.isAdmin(user.getUserId())) {
            perms.add("*:*:*");
        } else {
            List<SysRoleBo> roles = user.getRoles();
            if (CollectionUtil.isNotEmpty(roles) && roles.size() > 1) {
                // 多角色设置permissions属性，以便数据权限匹配权限
                for (SysRoleBo role : roles) {
                    Set<String> menuPerms = sysRoleService.listMenuPermById(role.getRoleId());
                    role.setPermissions(menuPerms);
                    perms.addAll(menuPerms);
                }
            } else {
                Set<String> menuPerms = sysUserService.listMenuPermById(user.getUserId());
                perms.addAll(menuPerms);
            }
        }
        return perms;
    }
}
